<template>
  <el-row class="node_welcone_msg_box">
    <div class="btn_box">
      <el-button type="primary" class="primary_btn" @click="saveEdit">{{$t('public.save')}}</el-button>
      <!--<el-button v-show="nodeObj._id && showDeleteBtn" type="primary" class="primary_btn delete_btn" @click="deleteLi">{{$t('public.delete')}}</el-button>-->
    </div>
    <el-form :model="nodeObj" label-width="100px" ref="nodeObj" :rules="rulesOne">
      <el-form-item class="form_li"  prop="name" :label="$t('configLazyLoad.process.nodeName')">
        <el-input :maxlength="30" v-model.trim="nodeObj.name" class="input_box node_name"></el-input>
      </el-form-item>
      <el-form-item prop="welcomeType"  :label="$t('configLazyLoad.process.welcome3')">
        <el-radio-group v-model="nodeObj.welcomeType" @change="welcomeTypeChange">
          <!--common, wechat, weibo-->
          <el-radio label="single">{{$t('configLazyLoad.process.welcome4')}}</el-radio>
          <el-radio label="many">{{$t('configLazyLoad.process.welcome5')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="欢迎语内容：">
        <div class="welcome_msg_editor_box">
          <el-col v-show="nodeType === 'many'" :span="7" class="msg_list_box">
            <div class="prompit">
              {{$t('channelsettings.schedule7')}}<br/>
              {{$t('configLazyLoad.process.welcome6')}}<br/>
              {{$t('configLazyLoad.process.welcome7')}}<br/>
              {{$t('configLazyLoad.process.welcome8')}}
            </div>
            <div class="msg_list_box_head">
              <span class="head_title" @click="addOne()"><i class="el-icon-plus"></i>{{$t('configLazyLoad.process.welcome9')}}</span>
            </div>
            <div v-for="(welcomeMsg, index) in welMsgUl" class="msg_list_box_body">
              <span class="title_border"></span>
              <span class="iconfont icon-beizhu todo_btn_edit" @click="editOne(index, welcomeMsg)"></span>
              <span class="todo_btn" @click="lessOne(index)" ><i class="el-icon-minus"></i></span>
              <div class="welcone_msg_box" v-html="welcomeMsg.content"></div>
              <div class="welcone_msg_time">{{$t('configLazyLoad.process.welcome10')}}{{welcomeMsg.startTime}}——{{welcomeMsg.endTime}}</div>
            </div>
          </el-col>
          <el-col :span="14" class="welcone_msg_edit_box" v-show="welcomeMsgEditShow">
            <el-form :model="editorClone" ref="editorClone">
              <el-row class="msg_time_box" v-show="nodeType === 'many'">
                <el-col :span="3" class="msg_time_box_title">{{$t('configLazyLoad.process.welcome10')}}</el-col>
                <el-col :span="9" class="start_input">
                  <el-form-item prop="startTime">
                    <el-input v-model.trim="editorClone.startTime" :placeholder="$t('configLazyLoad.process.welcome11')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="9">
                  <el-form-item prop="endTime">
                    <el-input v-model.trim="editorClone.endTime" :placeholder="$t('configLazyLoad.process.welcome12')"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div class="remark">
              <span>{{$t('configLazyLoad.process.welcome13')}}</span>
              <el-tooltip class="item" effect="dark" popper-class="reportTip" placement="bottom" style="opacity: 1;">
                <div slot="content">
                  {{$t('configLazyLoad.process.welcome14')}}
                  <br/>
                  {{$t('configLazyLoad.process.welcome15')}}
                </div>
                <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
              </el-tooltip>
            </div>
            <div class="placeholder_box">
              <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
                {{place.content}}
                <i class="iconfont icon-zhankai"></i>
              </dl>
            </div>
            <div id="welcomeMsgEditorMenu"></div>
            <div id="welcomeMsgEditorCon"></div>
            <div class="editor_btn_box" v-show="nodeType === 'many' && isEditor">
              <el-button type="primary" class="primary_btn save_welcome_msg" @click="saveWelcomeMsg">{{$t('configLazyLoad.process.welcome16')}}</el-button>
              <el-button type="primary" class="primary_btn delete_btn" @click="cancelUpdate">{{$t('configLazyLoad.process.welcome17')}}</el-button>
            </div>
          </el-col>
        </div>
      </el-form-item>
    </el-form>
  </el-row>
</template>
<script>
  import Editor from 'wangeditor'
  import * as uuid from 'uuid'
  import {uploadTo7moorEmailDomain} from '@utils/qiniuUtils'
  import * as types from '@modules/config/channelConfig/webchatSchdule/mutation-types.js'
  import { deepClone, filterXSS } from '@utils/m7Utils.js'
//  import nodeSelect from '../../../base/webchatNodeSelect.vue'
  export default {
    name: 'welcomeNodeEdit',
    data () {
      return {
        editorClone: {content: '', startTime: '', endTime: ''},
        editIndex: 0,
        welcomeMsgEditShow: false,
        isEditor: false,
        editor: {},
        editorType: '',
        placeholderArr: [
//          {
//            content: '访客ID：userId',
//            data: 'userId'
//          },
          {
            content: this.$t('configLazyLoad.process.welcome18'),
            data: 'nickName'
          }, {
            content: this.$t('configLazyLoad.process.welcome19'),
            data: 'agent'
          }, {
            content: this.$t('configLazyLoad.process.welcome20'),
            data: 'agentName'
          }, {
            content: this.$t('configLazyLoad.channel.agentNickName'),
            data: 'agentNickName'
          }, {
            content: this.$t('configLazyLoad.channel.agentPhone'),
            data: 'agentPhone'
          }
        ],
        welMsgUl: [],
        welMsg: '',
        optionsOne: [],
        rulesOne: {
          name: [
            { required: true, message: this.$t('configLazyLoad.process.processLabel7'), trigger: 'blur' }
          ],
          welcomeType: [
            { required: true, message: this.$t('configLazyLoad.process.welcome21'), trigger: 'change' }
          ]
        },
        nodeObj: {
          _id: '', // id
          account: '', // 账户id
          type: 'welcome', // 节点类型
          name: '', // 名称
          welcomeType: 'single', // 欢迎语类型  single 固定  many 多时段
          createTime: '', // 创建时间
          createUser: '', // 创建人
          updateTime: '', // 修改时间
          updateUser: '', // 修改人
          welcomeMessage: '',  // 固定时段欢迎语
          welcomeMessages: []
        },
        m7uploaders: []
      }
    },
    props: {
      showDeleteBtn: {
        type: Boolean,
        default: true
      },
      dataId: {
        type: String,
        default: ''
      },
      random: Number,
      todoType: String
    },
    methods: {
      initUploadImageFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          // self.editor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.editor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
          self.editorClone.content = self.editor.txt.html()
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'email/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorEmailDomain(this.sessionUserId, 'w-agent-node-img-icon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      initData () {
        if (this.dataId) {
          let data = {
            _id: this.dataId
          }
          this.$store.dispatch('getNodeById', data).then((res) => {
            if (res.success) {
              this.$nextTick(() => {
                this.nodeObj = deepClone(res.data)
                this.welMsgUl = deepClone(res.data.welcomeMessages)
                this.welMsg = deepClone(res.data.welcomeMessage)
                this.initEditor()
                if (this.nodeType === 'single') {
                  this.welcomeMsgEditShow = true
                } else {
                  this.welcomeMsgEditShow = false
                }
              })
            } else {
              this.welMsgUl = []
              this.welMsg = ''
            }
          })
        } else {
          this.nodeObj = {
            _id: '', // id
            account: '', // 账户id
            type: 'welcome', // 节点类型
            name: '', // 名称
            welcomeType: 'single', // 欢迎语类型
            createTime: '', // 创建时间
            createUser: '', // 创建人
            updateTime: '', // 修改时间
            updateUser: '', // 修改人
            welcomeMessage: '',
            welcomeMessages: []
          }
          this.welcomeMsgEditShow = true
          this.welMsgUl = []
          this.welMsg = ''
        }
//        可能会存在编辑完成之后未保存直接返回的操作，因此需要初始化的时候处理
        if (this.nodeType === 'many') {
          this.isEditor = false
        }
      },
      editOne (index, data) {
        console.log(this.welMsgUl)
        this.isEditor = true
//        this.$refs['editorClone'].resetFields()
        this.editIndex = index
        this.editorClone = deepClone(data)
        this.editor.txt.html(filterXSS(this.editorClone.content))
        this.editorType = 'update'
      },
      saveWelcomeMsg () {
        let that = this
        this.$refs['editorClone'].validate((valid) => {
          if (valid) {
            if (!this.transferForm(that.editorClone.startTime, that.editorClone.endTime)) {
              return
            }
            if (that.editorType === 'add') {
              that.welMsgUl.push(that.editorClone)
            } else {
              that.welMsgUl[this.editIndex] = that.editorClone
            }
//            that.$emit('messageArrChg', that.welMsgUl)
            that.isEditor = false
            that.editorClone = {content: '', startTime: '', endTime: ''}
          }
        })
      },
      cancelUpdate () {
//        this.$refs['editorClone'].resetFields()
        this.editorClone.content = ''
        this.editor.txt.html('')
        this.isEditor = false
      },
      addOne () {
//        this.$refs['editorClone'].resetFields()
        if (this.welMsgUl.length >= 6) {
          this.$message.error(this.$t('configLazyLoad.process.welcome22'))
          return
        }
        this.editorClone = {content: '', startTime: '', endTime: ''}
        this.editor.txt.html(filterXSS(this.editorClone.content))
        this.editorType = 'add'
        this.isEditor = true
      },
      lessOne (index) {
        this.welMsgUl.splice(index, 1)
//        this.$emit('messageArrChg', this.welMsgUl)
        this.isEditor = false
      },
      transferForm (start, end) {
        let datePattern = new RegExp(/^([01][0-9]|[2][0-3]):[0-5][0-9]$/)
        if (start === '') {
          this.$message.error(this.$t('configLazyLoad.process.timeNode14'))
          return false
        } else if (!datePattern.test(start) && start !== '*') {
          this.$message.error(this.$t('channelsettings.schedule31'))
          return false
        }
        if (end === '') {
          this.$message.error(this.$t('configLazyLoad.process.timeNode15'))
          return false
        } else if (!datePattern.test(end) && end !== '*') {
          this.$message.error(this.$t('channelsettings.schedule32'))
          return false
        }
        return true
      },
      initBox () {
        if (this.editor.txt) {
          this.editor.txt.html(filterXSS(this.welcomeMessage))
        }
      },
      onChange (data) {
        this.nodeObj[data.path] = data.value
      },
      resetForm () {
        this.$refs['nodeObj'].resetFields()
        this.initEditor()
      },
      initEditor () {
        if (this.editor.txt) {
          this.editor.txt.html(filterXSS(this.welMsg))
        }
      },
      welcomeTypeChange () {
        if (this.nodeType === 'single' || (this.isEditor && this.nodeType === 'many')) {
          this.welcomeMsgEditShow = true
        } else {
          this.welcomeMsgEditShow = false
        }
      },
      saveEdit () {
        let that = this
        this.$refs['nodeObj'].validate((valid) => {
          // 修复编辑器插入超链接时自动转义连接上的&符的问题
          if (that.nodeObj.welcomeType === 'single') {
            that.nodeObj.welcomeMessage = that.editor.txt.html()
            that.nodeObj.welcomeMessage = that.nodeObj.welcomeMessage.replace(/&amp;/g, '&')
          } else {
            if (that.isEditor) {
              this.$message.error(this.$t('configLazyLoad.process.welcome23'))
              return
            } else {
              that.nodeObj.welcomeMessages = that.welMsgUl
              that.nodeObj.welcomeMessages.forEach((item) => {
                item.content = item.content.replace(/&amp;/g, '&')
              })
            }
          }
          console.log(that.nodeObj)
          if (valid) {
            if (this.todoType === 'add') {
              that.$store.dispatch('addNode', that.nodeObj).then((res) => {
                if (res.success) {
                  that.$store.commit(types.ADD_WEBCHAT_SCHDULE_LIST_NODE, {node: 'welcomeNode', data: that.nodeObj})
                  this.$message.success(this.$t('configLazyLoad.qualityCheck.addSuccess'))
                  this.$emit('back')
                }
              })
            } else {
              that.$store.dispatch('updateNode', that.nodeObj).then((res) => {
                if (res.success) {
                  that.$store.commit(types.UPDATE_WEBCHAT_SCHDULE_LIST_NODE, {node: 'welcomeNode', data: that.nodeObj})
                  this.$message.success(this.$t('configLazyLoad.public.editSuccess'))
                  this.$emit('back')
                }
              })
            }
          }
        })
      },
      addPlaceholder (data) {
        let dataNew = ''
        let content = this.editor.txt.html()
        content = content.replace(/<p><br><\/p>/g, '')
        content = content.substring(0, content.length - 4)
        console.log(content)
        if (!content) {
          dataNew = '<p>{' + data + '}</p>'
        } else {
          dataNew = content + '{' + data + '}</p>'
        }
        this.editor.txt.html(filterXSS(dataNew))
        this.editorClone.content = dataNew
      }
    },
    watch: {
      isEditor (cur) {
        if (cur === true || this.nodeType === 'single') {
          this.welcomeMsgEditShow = true
        } else {
          this.welcomeMsgEditShow = false
        }
      },
//      welcomeMessage (cur) {
//        this.welMsg = cur
//      },
//      welcomeMessages (cur) {
//        this.welMsgUl = cur
//      },
      random () {
        this.initData()
        this.resetForm()
      }
    },
    computed: {
      sessionUserId () {
        return this.$store.state.session.user._id
      },
      nodeType () {
        return this.nodeObj.welcomeType
      }
    },
    mounted () {
      this.editor = new Editor('#welcomeMsgEditorMenu', '#welcomeMsgEditorCon')
      this.editor.config.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'justify'  // 对齐方式
      ]
      this.editor.config.pasteTextHandle = filterXSS
      this.editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
      let that = this
      let lang = window.langJson || {}
      let editLang = lang.wangeditor
      this.editor.config.lang = editLang
      this.editor.config.onchange = (html) => {
        // html 即变化之后的内容
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(that.editorClone.content)) {
          that.editorClone.content = that.subContent.content.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
        }
        that.editorClone.content = that.editor.txt.html()
      }
      this.editor.config.zIndex = 100
      this.editor.create()
      this.editor.txt.html(filterXSS(that.editorClone.content))
      let div = document.createElement('div')
      div.className = 'w-e-menu'
      div.style.cssText = 'z-index:101;'
      let span = document.createElement('i')
      span.className = 'w-e-icon-image'
      span.id = 'w-agent-node-img-icon'
      div.appendChild(span)
      document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
      this.initUploadImageFile()
      this.initBox()
    },
    components: {
//      nodeSelect
    },
    beforeMount () {
      this.initBox()
      this.initData()
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    }
  }

</script>
<style lang="stylus" scoped>
  @import "../../../../../../../assets/common.styl"
  .btn_box
    text-align right
    margin-bottom 10px
    padding 10px
  .delete_btn
    background-color #ff6b6b
    border-color #ff6b6b
  .todo_btn
    cursor pointer
    position absolute
    right 8px
    color $c-main
  .node_name
    width 400px
  .start_input
    position relative
    margin-right 24px
    &:before
      content: ''
      border-top 2px solid $c-border2
      width 16px
      position absolute
      top 15px
      right -20px
  .welcome_msg_editor_box
    font-size 12px
    line-height 20px
  .prompit
    color $c-prompt
    padding 6px 0 12px
  .msg_list_box_head
    background #f4f4f4
    height 50px
    line-height 50px
    padding-left 20px
    .head_title
      cursor pointer
  .el-icon-plus
    margin-right 10px
    color $c-main
  .msg_time_box
    margin 8px 0 10px 0
    .msg_time_box_title
      line-height 40px
    .input_box
      width 120px
      display inline-block
  .msg_list_box_body
    position relative
    padding 8px 50px 8px 8px
    background #f4f4f4
    .todo_btn,.todo_btn_edit
      cursor pointer
      position absolute
      right 6px
      color $c-main
    .todo_btn_edit
      right 26px
    .welcone_msg_box
      width 100%
      word-break break-all
      color #737373
      img
        max-width 100%
  .title_border
    position absolute
    height 1px
    background #ccc
    width 96%
    margin 0 auto
    display inline-block
    top 0
  .welcone_msg_col
    position relative
    .icon-beizhu
      position absolute
      cursor pointer
      right 4px
      top 0
      color $c-main
  .start_input
    position relative
    margin-right 24px
    &:before
      content: ''
      border-top 2px solid $c-border2
      width 16px
      position absolute
      top 15px
      right -20px
  .welcone_msg_edit_box
    padding-top 6px
  .save_welcome_msg
    margin-top 10px
  .w-e-toolbar
    background-color #f1f1f1
    border 1px solid #ccc
  #welcomeMsgEditorCon
    border 1px solid #ccc
    border-top none
    height 220px
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height:16px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
  .msg_list_box
    margin-right 30px
</style>
